#!/bin/bash
export PATH=/home/postgres/psql14/bin:$PATH
export PGDATABASE=postgres
export PGHOST=127.0.0.1
export PGUSER=postgres
export PGPORT=15433
export PGPASSWORD=123456
slaveDataDir=/home/postgres/slavedata/pgdata
slaveConninfo='application_name=pushstandby user=repl password=123456 host=127.0.0.1 port=15433 sslmode=disable sslcompression=0 gssencmode=disable target_session_attrs=any'
pushDataDir=/home/postgres/data/pgdata
pushImdbPageDirectory=/tmp/pushpagedb
pushImdbWalDirectory=/tmp/pushwaldb
pushLogfile=/home/postgres/logfile2

pg_ctl -D $pushDataDir -l $pushLogfile stop
if [ $? -ne 0 ]
then
    echo "$(date "+%F %T"): He3DB push instance stop failed!"
    exit 1
fi

sed -i 's/^primary_conninfo/#primary_conninfo/g' $pushDataDir/postgresql.auto.conf
sed -i 's/^primary_conninfo/#primary_conninfo/g' $pushDataDir/postgresql.conf

echo -e "primary_conninfo = '$slaveConninfo'" >> $pushDataDir/postgresql.conf

sed -i 's/^hot_standby/#hot_standby/g' $slaveDataDir/postgresql.conf
sed -i 's/^primary_conninfo/#primary_conninfo/g' $slaveDataDir/postgresql.auto.conf
sed -i 's/^primary_conninfo/#primary_conninfo/g' $slaveDataDir/postgresql.conf

echo -e "hot_standby=off" >> $slaveDataDir/postgresql.conf

psql -c 'SELECT pg_promote(true, 30)'
if [ $? -ne 0 ]
then
    echo "$(date "+%F %T"): He3DB slave instance promote failed!"
    exit 1
fi

rm -rf $pushImdbPageDirectory $pushImdbWalDirectory
pg_ctl -D $pushDataDir -l $pushLogfile start
if [ $? -ne 0 ]
then
    echo "$(date "+%F %T"): He3DB push instance start failed!"
    exit 1
fi